/*
@hehung
2023-5-22
email: 1398660197@qq.com
wechat: hehung95
reproduced and please indicate the source @hehung
*/
#include "app_common.h"

static volatile bool uart4_send_complete_flag = false;
static volatile bool uart4_recv_complete_flag = false;
static volatile uint32_t uart4_recv_char = '\0';


// Uart initialize
void Uart_Init(void)
{
	fsp_err_t err = FSP_SUCCESS;
	
	/* Open the transfer instance with initial configuration. */
    err = R_SCI_UART_Open(&g_uart4_ctrl, &g_uart4_cfg);
    assert(FSP_SUCCESS == err);
}

// callback function for uart9
void uart4_notification(uart_callback_args_t * p_args)
{
	if (p_args->event == UART_EVENT_TX_COMPLETE)
	{
		uart4_send_complete_flag = true;
	}
	else if (p_args->event == UART_EVENT_RX_CHAR)
	{
		uart4_recv_char = p_args->data;
		uart4_recv_complete_flag = true;
	}
}

// fputs for printf or other print function in standard
int fputc(int ch, FILE *f)
{
	fsp_err_t err = FSP_SUCCESS;
	
	(void)f;
	err = R_SCI_UART_Write(&g_uart4_ctrl, (uint8_t *)&ch, 1);
	if(FSP_SUCCESS != err) 
		__BKPT();
	/* Waiting until transmit finished */
	while(uart4_send_complete_flag == false) 
	{}
	uart4_send_complete_flag = false;
	
    return ch;
}

// fgets for scanf or other input function in standard
int fgetc(FILE *f) 
{	
	(void)f;
	
	while (uart4_recv_complete_flag == false)
	{}
	uart4_recv_complete_flag = false;

	return (int)uart4_recv_char;
}
